import urls from '/util/urls'
import request from '/util/request'
import { parseTime} from '/util/utils'

Page({
  data: {
    sId:'',
    taskList:[],
    normalList:['正常','异常'],
    status: false
  },
  onLoad(options) {
    let that = this
    // 传递的参数
    const id = options.id
    // 加载巡检的详细信息
    request.get(urls.inspectionServiceReportListUrl(id), function(data){
       const saveList = data.filter(l => l.status === 'toBeReported')
       that.setData({
        sId:id,
        status:saveList.length > 0 ? true : false,
        taskList:data.map(l =>{
          return {
            id:l.id,
            code: l.code,
            reportPersonCode: l.reportPersonCode,
            reportPersonName: l.reportPersonName,
            unitCode: l.unitCode,
            startTime: parseTime(l.startTime, '{y}-{m}-{d}'),
            s_startTime:l.startTime,
            endTime: l.endTime,
            cronExp: l.cronExp,
            sorting: l.sorting,
            normal: l.normal,
            abnormalSituation: l.abnormalSituation,
            status:l.status
          }
        })
      })
    })
  },
  forInput(e){
    this.setData({
      ['taskList['+e.target.dataset.field+'].abnormalSituation'] :  e.detail.value
    });
  },
  forClear(e){
    this.setData({
      ['taskList['+e.target.dataset.field+'].abnormalSituation'] : ''
    });
  },
    // 选择值的时候发生变化
  radioChange(e) {
    const index  = e.target.dataset.field
    this.data.taskList[index].normal = e.detail.value == '正常' ? true :false
  },
  onSubmit() {
   const that = this
   const saveList = that.data.taskList.filter(l => l.status === 'toBeReported')

   if(saveList){
     dd.showLoading({
      content: '提交中...',
    })
    saveList.forEach(l =>{
      const formData = {
        id:l.id,
        code: l.code,
        reportPersonCode: l.reportPersonCode,
        reportPersonName: l.reportPersonName,
        unitCode: l.unitCode,
        startTime: new Date(l.s_startTime).getTime(),
        endTime: l.endTime,
        cronExp: l.cronExp,
        sorting: l.sorting,
        normal: l.normal,
        abnormalSituation: l.abnormalSituation,
        status:l.status
      }
      request.put(urls.inspectionServiceReportUrl(l.id), formData, () => {
        dd.hideLoading()
        dd.showToast({
          type: 'success',
          content: '提交成功',
          duration: 2000,
          success: () => {
            dd.redirectTo({
              url: '/pages/inspection/insurance/insurance?id=' + that.data.sId
            })
          },
        })
      }, () => {
        dd.hideLoading()
        dd.showToast({
          type: 'fail',
          content: '提交失败',
          duration: 2000,
        })
      })
    })
   }
  },
  back(){
    const that = this
    dd.redirectTo({
      url: '/pages/inspection/insurance/insurance?id=' + that.data.sId
    })
  }
});
